<template>
	<view class="spring d_flex a_c" :class="{isSpell:isSpell===false}" @click="spell(data)">
		<template v-if="data.languageType===2">
			<text v-if="data.usaSoundmark">[{{data.usaSoundmark}}]</text>
			<text v-if="data.roman" style="margin: 0 4px; ">[{{data.roman}}]</text>
		</template>
		<text v-if="data.languageType===2">
			{{strs.map((key)=>toneMaps[key]?toneMaps[key].title:'').join()}}
		</text>
		<text v-else>
			{{ukSoundmark.join()}}
		</text>
		<image v-if="isSpell!==false" src="/static/lb.png"></image>
	</view>
</template>

<script>
	import {toneMaps} from '@/util/status.js'
	let innerAudioContext;
	export default {
		name:"wordphonetic",
		props:{
			data:Object,
			isSpell:{
				type:Boolean,
				default:true
			}
		},
		data() {
			return {
				toneMaps,
				ukSoundmark:[],
				strs:[]
			};
		},
		watch:{
			data(){
				this.foramtData();
			}
		},
		mounted(){
			this.foramtData();
			if(!innerAudioContext){
				innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.onError(res => {
					console.log(res.errMsg);
					console.log(res.errCode);
				});
			}
		},
		methods:{
			foramtData(){
				let usaSoundmark=[];
				if(typeof this.data.usaSoundmark==="string"){
					usaSoundmark = this.data.usaSoundmark.split(",");
					usaSoundmark = usaSoundmark.filter((val)=>val);
				}
				if(typeof this.data.ukSoundmark==="string"){
					this.strs = this.data.ukSoundmark.split(",");
					this.strs = this.strs.filter((val)=>val);
				}
				this.ukSoundmark = usaSoundmark;
			},
			//拼读
			spell(item) {
				if(this.isSpell===false){
					return;
				}
				let that = this;
				
				this.$http
					.gettts('api/client/word/tts', {
						wordStr: item.name || item.wordStr,
						langType:this.data.languageType===2?'ja':'en'
					})
					.then(res => {
						const fs = wx.getFileSystemManager();
						const basePath = `${wx.env.USER_DATA_PATH}/audio`;
						const audioPath = `${basePath}/${new Date().getTime()}.mp3`;
						let hasFolder = true;
						try {
							fs.accessSync(basePath);
						} catch (e) {
							hasFolder = false;
						}
						// 没有则先创建audio文件夹
						if (!hasFolder) {
							fs.mkdir({
								dirPath: basePath
							});
						}
						fs.writeFile({
							filePath: audioPath,
							data: res,
							encoding: 'binary',
							success: res => {
								innerAudioContext.src = audioPath;
								innerAudioContext.onPlay(() => {
									console.log('开始播放');
									
								});
								setTimeout(()=>{
									innerAudioContext.stop();	
								},1000)
							}
						});
					});
			},
		}
	}
</script>

<style lang="scss">
.spring {
				font-size: 28rpx;
				color: #575A64;
				margin: 20rpx 0;

				image {
					position: relative;
					// top: 6rpx;
					width: 32rpx;
					height: 32rpx;
					margin-left: 20rpx;
				}
			}
.isSpell{
	margin:0 !important;
}
</style>